﻿using System;
using System.Globalization;
using System.Linq;
using System.Web.Mvc;
using FPP.Models;
using FPP.Custom;
using System.Web.Security;
using FPP.Utilities;


namespace FPP.Controllers
{
    public class UserController : BaseController
    {

        //
        // GET: /User/

        [HandleError]
        public ActionResult Index()
        {
            if (HttpContext.Request.Url != null)
            {
                var currentUrl = HttpContext.Request.Url.AbsoluteUri;
                if (!currentUrl.Contains("www") && !(currentUrl.Contains("localhost")))
                {
                    currentUrl = (currentUrl.Contains("http://"))
                                     ? currentUrl.Replace("http://", "http://www.")
                                     : currentUrl.Replace("https://", "https://www.");
                    Response.Redirect(currentUrl);
                    return View();
                }
            }


            if (Facebook.Web.FacebookWebContext.Current.UserId != 0)
            {
                provider.FacebookLogin(int.Parse(Facebook.Web.FacebookWebContext.Current.UserId.ToString(CultureInfo.InvariantCulture)));
                FormsAuthentication.SetAuthCookie(provider.SessionId, false);
                Session.Add("currentUser", GetUserFromLoginToken(provider.SessionId));
            }

            //if a user was sent here from another url, send them back where they came from.
            var _return = Request.QueryString["returnURL"];
            if (HttpContext.Session != null) HttpContext.Session.Add("returnURL", _return);

            var user = new User();
            if (HttpContext.User.Identity.IsAuthenticated && Session["USER"] != null)
            {
                user = (User)Session["USER"];
                return View("Details", user);
            }

            return View(user);
        }


        public bool KickBadActivity(int attemptedAccessId)
        {
            if (HttpContext.User.Identity.IsAuthenticated)
            {
                User user = GetUserFromLoginToken(HttpContext.User.Identity.Name);
                if (user.Id != attemptedAccessId)
                {
                    return true;
                }
            }
            return false;
        }

        // Attemps to login the user
        // POST: /User/Login

        [HttpPost]
        public ActionResult Index(string email, string password)
        {
            if (!ValidateLogin(email, password))
            {
                return View();
            }

            FormsAuthentication.SetAuthCookie(provider.SessionId, false);
            Session.Add("currentUser", GetUserFromLoginToken(provider.SessionId));

            //if there is a return URL, send the user back
            if (!string.IsNullOrEmpty(Request.QueryString["returnURL"]))
                Response.Redirect(Request.QueryString["returnURL"]);

            return RedirectToAction("Details", new { id = GetUserFromLoginToken(provider.SessionId).Id });
        }


        //
        // GET: /User/Details/5

        [CustomAuthorize]
        public ActionResult Details(int id)
        {
            if (KickBadActivity(id)) return Index();
            User user;

            using (context)
            {
                user = context.Users.FirstOrDefault(q => q.Id == id);
            }

            return View("Details", user);
        }

        public void FillFbRegister(User newuser)
        {

            var sr = Facebook.Web.FacebookWebContext.Current.SignedRequest;
            var d = (Facebook.JsonObject)sr.Data;
            var reg = (Facebook.JsonObject)d["registration"];
            var regName = reg["name"].ToString();
            //var regNameSplit = regName.Split(char.Parse(" "));
            //newuser.fb_oauth_token = d["oauth_token"].ToString();
            //var lastName = (regNameSplit.Length > 1) ? regName.Replace(regNameSplit[1], "") : "";
            newuser.FirstName = regName;
            newuser.LastName = "";
            newuser.Email = reg["email"].ToString();
            newuser.Password = reg["password"].ToString();
            newuser.fb_user_id = sr.UserId;
        }

        //
        // GET: /User/Create
        public ActionResult Create()
        {
            if (Request.HttpMethod == "GET")
                return View();

            var newuser = new User();
            FillFbRegister(newuser);

            var qContext = new fppEntities(DataAccess.ffpCString);
            using (qContext)
            {
                if (qContext.Users.Count(u => u.Email == newuser.Email) > 0)
                {
                    TempData["message"] = "Email address is currently in use.";

                    //syncs fb account to local account
                    if (newuser.fb_user_id != 0)
                    {
                        var updateUser = qContext.Users.First(u => u.Email == newuser.Email);
                        updateUser.FirstName = newuser.FirstName;
                        updateUser.LastName = "";
                        updateUser.Password = Secure.Encryption.Encrypt(newuser.Password);
                        updateUser.fb_user_id = newuser.fb_user_id;
                        qContext.ForceSave(updateUser);
                        TempData["message"] = "Account has been synced with facebook.";

                    }

                    return View();
                }

                newuser.Password = Secure.Encryption.Encrypt(newuser.Password);
                qContext.Users.AddObject(newuser);
                qContext.SaveChanges();

                TempData["message"] = "Account created successfully, please log in.";
                return RedirectToAction("Index");
            }
        }

        //
        // GET: /User/Edit/5

        public ActionResult Edit(int id)
        {
            if (KickBadActivity(id)) return Index();

            User user;

            using (context)
            {
                user = context.Users.FirstOrDefault(q => q.Id == id);
            }

            return View(user);
        }

        //
        // POST: /User/Edit/5

        [HttpPost]
        [CustomAuthorize]
        public ActionResult Edit(int id, FormCollection collection)
        {
            if (KickBadActivity(id)) return Index();

            try
            {

                using (var qContext = new fppEntities(DataAccess.ffpCString))
                {
                    var user = qContext.Users.FirstOrDefault(q => q.Id == id);
                    if (user != null)
                    {
                        user.FirstName = collection["FirstName"];
                        user.LastName = collection["LastName"];
                        var fbAvatarAnswer = collection["fbDisplayAvatar"];
                        user.fbDisplayAvatar = (string.IsNullOrEmpty(fbAvatarAnswer)) ? (bool?)null : bool.Parse(fbAvatarAnswer);
                        qContext.ForceSave(user);
                    }
                    RedirectToAction("Details", new { id });
                }

                return RedirectToAction("Details", new { id });
            }
            catch (Exception)
            {
                return View();
            }
        }

        public void Logout()
        {
            Session.Clear();
            FormsAuthentication.SignOut();

            HttpContext.Response.Redirect("/User", true);
        }


        private bool ValidateLogin(string email, string password)
        {

            if (!provider.ValidateUser(email, Secure.Encryption.Encrypt(password)))
            {
                ModelState.AddModelError("_FORM", "Unknown username and/or password");
            }

            return ModelState.IsValid;
        }

    }
}
